//
//  BuddyStatusPacketProcess.m
//  HiQ
//
//  Created by shoguncao on 12-8-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BuddyStatusPacketProcess.h"
#import "MainWindowController.h"
#import "Buddy.h"
#import "BuddyGroup.h"

@implementation BuddyStatusPacketProcess

// 接到好友上、下线提醒包的处理
- (void)onReceiveBuddyStatusNotify:(NSData *)data
{
    STATUSNOTIFYHRD *reply = (STATUSNOTIFYHRD *)[data bytes];
    
    if (reply->error != ERR_NO_ERROR)
        return;
    
    NSInteger userid_len = reply->userid_len;
    NSInteger userip_len = reply->userip_len;
    
    char *userIdChar = (char *)reply + sizeof(STATUSNOTIFYHRD);
    NSData *userIdData = [[NSData alloc] initWithBytes:userIdChar length:userid_len];
    NSString *userIdStr = [NSKeyedUnarchiver unarchiveObjectWithData:userIdData];
    NSInteger userId = [userIdStr intValue];
    
    char *userIpChar = (char *)reply + sizeof(STATUSNOTIFYHRD) + userid_len;
    NSData *userIpData = [[NSData alloc] initWithBytes:userIpChar length:userip_len];
    NSString *userIpStr = [NSKeyedUnarchiver unarchiveObjectWithData:userIpData];
    
    BuddyGroup *firstBuddyGroup = [[[[MainWindowController sharedMainWindowController] buddySource] buddyGroupArray] objectAtIndex:0];
    for (NSInteger i=0; i<[firstBuddyGroup->buddyList count]; ++i)  // 遍历好友列表，找到发送上、下线提醒的好友
    {
        Buddy *buddy = [firstBuddyGroup->buddyList objectAtIndex:i];
        if (buddy->buddyQQ == userId)
        {
            if (reply->operation == OP_STATUS_NOTIFY_ONLINE)
            {
                buddy->status = BUDDY_STATUS_ONLINE;
            }
            else if (reply->operation == OP_STATUS_NOTIFY_OFFLINE)
            {
                buddy->status = BUDDY_STATUS_OFFLINE;
            }
            buddy->ip = userIpStr;
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:ReloadBuddyListNotification object:nil userInfo:nil];
                [[[MainWindowController sharedMainWindowController] buddyOutlineView] reloadData];
            });
            break;
        }
    }  
    

    NSMutableArray *clusterChatArray = [[MainWindowController sharedMainWindowController] clusterChatArray];
    for (ClusterChatWindowController *controller in clusterChatArray) {
            for (Buddy *buddy in [[[controller clusterChatSource] _cluster] memberList]) 
            {
                if ([buddy buddyQQ] == userId) 
                {
                    if (reply->operation == OP_STATUS_NOTIFY_ONLINE)
                    {
                        buddy->status = BUDDY_STATUS_ONLINE;
                    }
                    else if (reply->operation == OP_STATUS_NOTIFY_OFFLINE)
                    {
                        buddy->status = BUDDY_STATUS_OFFLINE;
                    }
                    buddy->ip = userIpStr;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [controller RefreshMemberList];
                        [[controller tableClusterMember] reloadData];                        
                    });
                    break;
                 }
            }
    }
}

// 向服务器发送下线信息
- (void)onOffLine:(NSNotification*)notification
{
    Buddy *owner = [[MainWindowController sharedMainWindowController] myselfInfo];
    NSInteger qqNum = owner->buddyQQ;
    NSString *qqNumStr = [self convertQQNumToString:qqNum];
    NSData *qqNumData = [NSKeyedArchiver archivedDataWithRootObject:qqNumStr];
    
    // 构造下线通知包
    ONOFFLINEHRD *hrd = (ONOFFLINEHRD *)NewPtr(sizeof(ONOFFLINEHRD) + [qqNumData length]);
    hrd->type = CMD_FUN_STATUSNOTIFY;
    hrd->operation = OP_STATUS_NOTIFY_OFFLINE;
    hrd->userid_len = [qqNumData length];
    
    char *userIdChar = (char *)hrd + sizeof(ONOFFLINEHRD);
    [qqNumData getBytes:userIdChar length:[qqNumData length]];
    
    NSData *sendData = [[NSData alloc] initWithBytes:&(hrd->userid_len) length:(sizeof(NSInteger)+[qqNumData length])];
    [[Connection sharedServerConnection] sendData:sendData cmd:hrd->type subcmd:hrd->operation];
    DisposePtr((char *)hrd);
}

// 把 NSInteger 的qq号转换为 NSString 的
- (NSString *)convertQQNumToString:(NSInteger)qqNum
{
    NSMutableString *qqNumStr = [[NSMutableString alloc] initWithFormat:@"%ld", qqNum];
    while ([qqNumStr length] != QQ_NUM_LEN)
    {
        [qqNumStr insertString:@"0" atIndex:0];
    }
    return qqNumStr;
}

@end
